import { constantRoutes, asyncRoutes } from '@/router'
import Layout from '@/layout'

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, menuPermissions) {
    return new Promise(resolve => {
      const permissionMap = {}
      menuPermissions.forEach(menu => {
        if (menu.permission) {
          permissionMap[menu.permission] = true
        }
      })

      // 将菜单权限转换为路由格式
      const accessedRoutes = menuPermissions
        .filter(menu => menu.type === 1 && menu.parentId === 0)
        .map(menu => {
          const route = {
            path: menu.path,
            component: Layout,
            name: menu.name,
            meta: {
              title: menu.name,
              icon: menu.icon
            },
            children: []
          }

          // 添加子路由
          const children = menuPermissions.filter(item => 
            item.type === 1 && 
            item.parentId === menu.id
          )

          if (children.length > 0) {
            route.children = children.map(child => ({
              path: child.path,
              name: child.name,
              component: loadView(child.component),
              meta: {
                title: child.name,
                icon: child.icon
              }
            }))
          }

          return route
        })

      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

// 动态加载组件
function loadView(component) {
  if (!component) return null
  try {
    // 移除开头的 @ 符号和 .vue 后缀
    const path = component.replace(/^@/, '').replace(/\.vue$/, '')
    return () => import(`@/views${path}`)
  } catch (error) {
    console.error('加载组件失败:', error)
    return null
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 